package com.wocai.jrt.orgadmin.issuers.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.security.spi.cache.SecurityPublisherUserCache;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.admin.common.constant.ComConst;
import com.wocai.jrt.orgadmin.issuers.bean.IssuersResBean;
import com.wocai.jrt.orgadmin.issuers.bean.IssuersUpdateBean;
import com.wocai.jrt.orgadmin.issuers.bean.ResetPasswordReqBean;
import com.wocai.jrt.orgadmin.issuers.model.Issuers;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 发行方控制器
 * 
 * @author yinlei
 * @date 2016-3-7 15:37:31
 */
@Controller
@RequestMapping("/issuers")
public class IssuersAction extends GenericAction<Issuers> {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(IssuersAction.class);

	@Inject
	private IssuersService issuersServiceImpl;
	@Inject
	private PasswordEncoder bcryptPasswordEncoder;
	@Inject
	private SecurityPublisherUserCache securityPublisherUserCache;
	
	/**
	 * 获得发行方List，初始化列表页。
	 * 
	 * @param model
	 *            参数
	 * @return 发行方List
	 */
	@RequestMapping("/list")
	public String initial(Issuers model, Map<String, Object> maps) {
		// try {
		// LOGGER.info("query list param: [{}]",JSON.toJSONString(model));
		// List<Issuers> list = issuersServiceImpl.pagedList(model);
		// maps.put("list", list);
		// } catch (Exception e) {
		// LOGGER.error("get record list error, errorMsg=[{}].",
		// e.getMessage());
		// return "common/error";
		// }
		return "issuers/list";
	}

	@ResponseBody
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public Map<String, Object> query(@RequestBody Issuers model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
//			LOGGER.info("query issuers list param: [{}]",
//					JSON.toJSONString(model));
			model.setOrderBy("create_time desc");
			List<IssuersResBean> list = issuersServiceImpl
					.queryIssuersList(model);
			
			// 统计的时候，不需要分页
			model.setStart(null);
			long totalRecord = issuersServiceImpl.countBy(model);

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("issuers query success.");
			}

			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("issuers query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(@RequestBody Issuers model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isAnyBlank(model.getName(), model.getContacts(),
				model.getContactWay(), model.getAccount(), model.getPassword())) {
			bean.setCode(0);
			bean.setMessage("请检查参数是否完整");
			return bean;
		}
		if (!model.getPassword().equals(model.getPasswordConfirm())) {
			bean.setCode(0);
			bean.setMessage("请确认密码及确认");
			return bean;
		}
		try {
			// 设置基本参数 加密密码
			model.setId(ObjectId.get().toString());
			model.setCreateTime(new Date());
			model.setDisable(false);
			model.setOrgCode(UserUtils.getOrgCode());
			model.setOrgId(UserUtils.getOrgId());
			model.setPassword(bcryptPasswordEncoder.encode(model.getPassword()));

			int result = issuersServiceImpl.save(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 启用、禁用
	 * 
	 * @param model
	 * @return 操作结果
	 */
	@ResponseBody
	@RequestMapping("/disable")
	public JsonBean disable(@RequestBody IssuersUpdateBean model, HttpServletRequest request) {
		JsonBean bean = new JsonBean();
		if (null == model.getDisable()) {
			bean.setCode(0);
			bean.setMessage("数据有误");
			return bean;
		}
		try {
			model.setModefiedTime(new Date());
			int result = issuersServiceImpl.updateByBean(model);
			if (result == 1) {
				if (model.getDisable() == true) {
					getHttpSession().removeAttribute(ComConst.CONTEXT_PUBLISHER);
					Issuers issuers = issuersServiceImpl.get(model.getId());
					securityPublisherUserCache.removeUserFromCache(issuers.getAccount(), issuers.getTenantCode());
				}
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				if (LOGGER.isInfoEnabled()) {
					LOGGER.info("disable opreation success.");
				}
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("disable opreation error.");
			}
		} catch (Exception e) {
			LOGGER.error("disable opreation error, errorMsg=[{}].",
					e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 更新发行方密码
	 * 
	 * @param model
	 *            重置的发行方密码
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/resetPassword")
	public JsonBean resetPassword(@RequestBody ResetPasswordReqBean model) {
		JsonBean bean = new JsonBean();
		String passwordConfirm = model.getPasswordConfirm();
		String id = model.getId();
		String password = model.getPassword();
		if (StringUtils.isAnyBlank(passwordConfirm, id, password)) {
			bean.setCode(0);
			bean.setMessage("输入的参数有误，请检查");
			return bean;
		}
		if (!password.equals(passwordConfirm)) {
			bean.setCode(0);
			bean.setMessage("两次输入密码不一致，请检查");
			return bean;
		}
		try {
			Issuers iss = new Issuers();
			iss.setId(id);
			iss.setPassword(bcryptPasswordEncoder.encode(password));
			iss.setModefiedTime(new Date());
			int result = issuersServiceImpl.updateById(iss);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 更新发行方信息
	 * 
	 * @param model
	 *            要更新的发行方信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(@RequestBody IssuersUpdateBean model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isAnyBlank(model.getId(), model.getName(),
				model.getContacts(), model.getContactWay())) {
			bean.setCode(0);
			bean.setMessage("输入的参数有误，请检查");
			return bean;
		}
		try {
			model.setModefiedTime(new Date());
			int result = issuersServiceImpl.updateByBean(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 对数据进行验证
	 * 
	 * @param model
	 *            待验证的参数
	 * @param errors
	 *            验证结果
	 * @return true成功，false失败
	 */
	@ResponseBody
	@RequestMapping("/check")
	public boolean check(Issuers model, Integer type) {
		if (type == null) {
			return false;
		}
		if (type == 1) { // 编码
			if (model.getName() == null) {
				return false;
			}
		} else if (type == 2) {
			if (model.getAccount() == null) {
				return false;
			}
		} else if (type == 3) {
			if (model.getName() == null) {
				return false;
			} else {
				Issuers old = new Issuers();
				old = issuersServiceImpl.get(model.getId());
				String oldId = old.getName();
				if (oldId.equals(model.getName())) {
					return true;
				} else {
					model.setId(null);
				}
			}
		} 
		model.setOrgId(UserUtils.getOrgId());
		int result = issuersServiceImpl.countBy(model);
		// 已经存在了
		if (result >= 1) {
			return false;
		}
		return true;
	}
}
